import os
import json

import torch
from PIL import Image
from torchvision import transforms
import matplotlib.pyplot as plt

from vit_model import vit_base_patch16_224_in21k as create_model

def readimg():
    path_predict = 'F:\\python\\visiontr\\test_image'
    path_predict_list = []
    for i in os.listdir(path_predict):
        path_img = os.path.join(i)
        # path_img = os.path.join(path_predict,i)
        path_predict_list.append(path_img)
    return path_predict_list
# abc = readimg()
# print(abc)

def main(img_name):
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

    data_transform = transforms.Compose(
        [transforms.Resize(256),
         transforms.CenterCrop(224),
         transforms.ToTensor(),
         transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])])

    # load image
    img_path = 'F:\\python\\visiontr\\test_image\\' + img_name
    # print(img_path)
    assert os.path.exists(img_path), "file: '{}' dose not exist.".format(img_path)
    img = Image.open(img_path)
    plt.imshow(img)
    # [N, C, H, W]
    img = data_transform(img)
    # expand batch dimension
    img = torch.unsqueeze(img, dim=0)

    # read class_indict
    
    json_path = 'F:\\python\\visiontr\\class_indices.json'
    # json_path = './class_indices.json'
    assert os.path.exists(json_path), "file: '{}' dose not exist.".format(json_path)

    json_file = open(json_path, "r")
    class_indict = json.load(json_file)

    # create model
    model = create_model(num_classes=3, has_logits=False).to(device)
    # load model weights
    model_weight_path = "F:\\python\\visiontr\\weights\\model-9.pth"
    # model_weight_path = "./weights/model-9.pth"
    model.load_state_dict(torch.load(model_weight_path, map_location=device))
    model.eval()
    with torch.no_grad():
        # predict class
        output = torch.squeeze(model(img.to(device))).cpu()
        predict = torch.softmax(output, dim=0)
        predict_cla = torch.argmax(predict).numpy()

    print_res = "class: {}   prob: {:.3}".format(class_indict[str(predict_cla)],
                                                 predict[predict_cla].numpy())
    plt.title(print_res)
    for i in range(len(predict)):
        print("class: {:10}   prob: {:.3}".format(class_indict[str(i)],
                                                  predict[i].numpy()))
    output_path = r'./output_predict'
    if not os.path.exists(output_path):
        os.mkdir(output_path)
    plt.savefig('./output_predict/' + img_name)
    # plt.show()

 
if __name__ == '__main__':
    abc = readimg()
    for i in range(len(abc)):
        main(abc[i])